#include <stdlib.h>
#include <string.h>

#include <debug.h>
#include <os_api.h>
#include <hal/gpio.h>
#include <hal/uart.h>

#define GPIO_GPS_VCC_EN GPIO_PIN_119
#define GPIO_GPS_LNA_EN GPIO_PIN_117

#define UART_RX_MSGQ_QUEUE_SIZE (100)

#define TASK_STACK_SIZE (10 * 1024)
static char _task_stack[TASK_STACK_SIZE];

OSMsgQRef uart2RxMsgQ;

static void uart2_init(void)
{
    hal_UartOpen(UART_PORT_2, 9600, uart2RxMsgQ);

    hal_GpioSetDir(GPIO_GPS_VCC_EN, GPIO_OUT_PIN);
    hal_GpioOut(GPIO_GPS_VCC_EN, 1);

    hal_GpioSetDir(GPIO_GPS_LNA_EN, GPIO_OUT_PIN);
    hal_GpioOut(GPIO_GPS_LNA_EN, 1);
}

static void app_task(void *param)
{
    UartRxMsg_Type uartRxMsg;

    LOG_PRINTF("%s()... start...", __FUNCTION__);

    sleep(3); // wait system ready.

    uart2_init();

    while (1)
    {
        memset(&uartRxMsg, 0, sizeof(uartRxMsg));
        OSAMsgQRecv(uart2RxMsgQ, (UINT8 *)&uartRxMsg, sizeof(uartRxMsg), OS_SUSPEND);

        hal_UartWrite(UART_PORT_3, uartRxMsg.data, uartRxMsg.length);
        free(uartRxMsg.data);
    }
}

int main()
{
    int ret;
    OSTaskRef task_ref; // because following task will never exit, so we do not use task handle, so we don't care it's handle

    /*create UART2 Rx task*/
    ret = OSAMsgQCreate(&uart2RxMsgQ, "uart2RxMsgQ", sizeof(UartRxMsg_Type), UART_RX_MSGQ_QUEUE_SIZE, OS_FIFO);
    ASSERT(ret == OS_SUCCESS);

    ret = OSATaskCreate(&task_ref, _task_stack, TASK_STACK_SIZE, OS_APP_PRIORITY, "app", app_task, NULL);
    ASSERT(ret == OS_SUCCESS);
}
